package cn.chendd.example.jpa.user.dao;

import cn.chendd.example.jpa.user.dto.UserResultDto;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Map;

/**
 * @author chendd
 * @date 2020/5/5 22:26
 */
@Repository
@Transactional(readOnly = true)
public class UserQueryCustomResultDao {

    @PersistenceContext
    private EntityManager entityManager;

    public List<Map<String , Object>> nativeSqlQuery2Map() {
        String sql = "select 7 age , 3.1415 pi , name userName , createTime createTime " +
                " from user a where a.name = ?";
        NativeQueryImpl query = entityManager.createNativeQuery(sql).unwrap(NativeQueryImpl.class);
        query.setParameter(1, "chendd");
        query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String, Object>> resultList = query.getResultList();
        return resultList;
    }

    public List<UserResultDto> nativeSqlQuery2Bean() {
        String sql = "select id, name userName , createTime , 3.1415 pi , 100.00 amount , 1 status" +
                " from user a where a.name = ?";
        NativeQueryImpl query = entityManager.createNativeQuery(sql).unwrap(NativeQueryImpl.class);
        query.setResultTransformer(Transformers.aliasToBean(UserResultDto.class));
        query.setParameter(1, "chendd");
        query.addScalar("id", StandardBasicTypes.STRING);
        query.addScalar("userName", StandardBasicTypes.STRING);
        query.addScalar("createTime", StandardBasicTypes.TIMESTAMP);
        query.addScalar("pi", StandardBasicTypes.DOUBLE);
        query.addScalar("amount", StandardBasicTypes.BIG_DECIMAL);
        /*query.addScalar("status", StandardBasicTypes.NUMERIC_BOOLEAN);*/
        query.addScalar("status" , StandardBasicTypes.BOOLEAN);
        List<UserResultDto> resultList = query.getResultList();
        return resultList;
    }

}
